package com.tianqu.tms.core.webservice;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.entity.User;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TmsXmlResolveController {
	private static Logger logger = Logger
			.getLogger(TmsXmlResolveController.class);// log

	/**
	 * 用户、权限数据同步服务器端
	 * 
	 * 
	 * 
	 * @return
	 */
	public static String user() {
		logger.debug("用户信息同步开始.........................");
	 
		TxController controller = TxController.getTxController();
		try {
			controller.begin();
			User user = User.getInstance();
		 
			List<User> list = user.findIpadUser();
			if (list.size() < 1) {
				controller.commit();
				return null;
			}
		 String xml = "<?xml version='1.0' encoding='utf-8'?><User>";
			for (int i = 0; i < list.size(); i++) {
				User use = list.get(i);
				xml +=  "<Users><UserId>" + use.getLoginId() + "</UserId>"
						+ "<Password>" + use.getPassword() + "</Password>"
						+ "<UserName>" + use.getRealName() + "</UserName>"
						+ "<UserClass>1</UserClass>" + "<UserRole>"
						+ 1 + "</UserRole></Users>";
			}
			xml+= "</User>"; 
		 
			controller.commit();
			return xml;
		} catch (TransactionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TmsDaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.debug("用户信息同步结束.........................");
		return "";
			
	}
	/**
	 * 交易车辆查验车辆基本信息、图片数据同步上传
	 * 
	 * @param serial
	 * @param licenseplate
	 * @param vin
	 * @param cyCardtype
	 *            号牌种类
	 * @param businesstype
	 *            业务类型
	 * @param vinnum
	 *            车辆识别代号
	 * @param enginenum
	 *            发动机型号/号码
	 * @param brandmodel
	 *            车辆品牌/型号
	 * @param cyColor
	 *            车身颜色
	 * @param cyPassenger
	 *            核定载人数
	 * @param cyCartype
	 *            车辆类型
	 * @param plateortireexterior
	 *            号牌/车辆外观形状
	 * @param tireIntact
	 *            轮胎完好情况
	 * @param seatbelt
	 *            安全带、三角警告牌
	 * @param numberAxes
	 *            外廓尺寸、轴数
	 * @param tiresize
	 *            轮胎规格
	 * @param lateralportionof
	 *            侧后部防护装置
	 * @param reflectivemark
	 *            车身反光标示
	 * @param fireextinguisher
	 *            灭火器
	 * @param drivingrecord
	 *            行驶记录装置
	 * @param security
	 *            安全出口、安全锤
	 * @param externalmarking
	 *            外部标示、文字
	 * @param siren
	 *            标志灯具、警报器
	 * @param securitytechnology
	 *            安全技术检验合格证明
	 * @param checkconclusion
	 *            查验结论
	 * @param photo_1
	 *            左前车图
	 * @param photo_2
	 *            右前车图
	 * @param photo_3
	 *            左后车图
	 * @param photo_4
	 *            右后车图
	 * @param userid
	 *            上传用户
	 * @param inserttime
	 *            查验时间
	 * @return
	 */
	public static String checkCarInfo(String serial,String flag, String licenseplate,
			String vin, String cyCardtype, String businesstype, String vinnum,
			String enginenum, String brandmodel, String cyColor,
			String cyPassenger, String cyCartype, String plateortireexterior,
			String tireIntact, String seatbelt, String numberAxes,
			String tiresize, String lateralportionof, String reflectivemark,
			String fireextinguisher, String drivingrecord, String security,
			String externalmarking, String siren, String securitytechnology,
			String checkconclusion, String photo_1, String photo_2,
			String photo_3, String photo_4, String userid, String inserttime) {
		logger.debug("车辆信息同步开始.........................");
		
		String status = "1";
		if(flag.equals(""))
		{
			status="2";
		    logger.debug("PAD查验标识为空!");
		    return status;
		}	
		
//		if(licenseplate.equals("")&& vin.equals(""))
//		{
//			status="2";
//		    logger.debug("PAD查验车牌号码和VIN码都为空!");
//		    return status;
//		}
		if(licenseplate.length()!=7 &&!licenseplate.equals(""))
		{
			status="2";
		    logger.debug("PAD查验车牌号码不是七位!");
		    return status;
		}	
		
		if("".equals(photo_1) && "".equals(photo_2) && "".equals(photo_3) && "".equals(photo_4) )
		{
			status="2";
		    logger.debug("PAD查验图片全部为空!");
		    return status;
		}	
		if(userid.equals(""))
		{
			status="2";
		    logger.debug("PAD查验图片userid为空!");
		    return status;
		}	
//		if(inserttime.equals(""))
//		{
//			status="2";
//		    logger.debug("PAD查验图片inserttime为空!");
//		    return status;
//		}
		try {
			TransferAcceptedInfo accept = new TransferAcceptedInfo();
			// 更新过户表
			accept.setSerial(serial);
			accept.setLicensePlate(licenseplate);
			accept.setVin(vin);
			if((serial!=null&&!"".equals(serial)) || (licenseplate!=null && !"".equals(licenseplate)))
			{
				TransferAcceptedInfo accept1 = new TransferAcceptedInfo();
				accept1 = accept1.searchAcceptInfoToPad(serial, licenseplate);
				if(accept1!=null)
				{
					accept.setSerial(accept1.getSerial());
					accept.setLicensePlate(accept1.getLicensePlate());
				}
			}
			
			if(cyCardtype!=null && !"".equals(cyCardtype))
			{
				accept.setCy_cardType(String.valueOf((Integer.parseInt(cyCardtype)-1)));
			}
     		if(businesstype!=null && !"".equals(businesstype))
     		{	
     			accept.setBusinessType(Integer.parseInt(businesstype));
     			//1.注册登记 2。转移登记 3.变更登记
     			if(businesstype.equals("1"))
     			{
     				accept.setRegistration(1);
     				accept.setTransferRegister(2);
     				accept.setChangesVacate(2);
     			}
     			if(businesstype.equals("2"))
     			{
     				accept.setTransferRegister(1);
     				accept.setRegistration(2);
     				accept.setChangesVacate(2);
     			}
     			if(businesstype.equals("3"))
     			{
     				accept.setChangesVacate(1);
     				accept.setTransferRegister(2);
     				accept.setRegistration(2);
     			}
     		}
			accept.setVinNum(vinnum);
			accept.setEngineNum(enginenum);
			accept.setBrandModel(brandmodel);
			accept.setCy_color(cyColor);
			accept.setCy_passenger(cyPassenger);
			accept.setCy_carType(cyCartype);
			accept.setPlateOrTireExterior(plateortireexterior);
			accept.setTireIntact(tireIntact);
			accept.setSeatBelt(seatbelt);
			accept.setNumberAxes(numberAxes);
			accept.setTireSize(tiresize);
			accept.setLateralPortionOf(lateralportionof);
			accept.setReflectiveMark(reflectivemark);
			accept.setFireExtinguisher(fireextinguisher);
			accept.setDrivingRecord(drivingrecord);
			accept.setSecurity(security);
			accept.setExternalMarking(externalmarking);
			accept.setSiren(siren);
			accept.setSecurityTechnology(securitytechnology);
			accept.setCheckConclusion(checkconclusion);
			accept.setStatus(1);
			User user = new User();
			user = user.getUserProfileByLoginid(userid, "");
			if(user!=null)
			{
				accept.setInsertUserid(user.getId());
				accept.setUpdateUserId(user.getId());
			}else{
				accept.setInsertUserid(1);
				accept.setUpdateUserId(1);
			}
			accept.setInsertTime(DateUtil.getStringToTimeStamp1(DateUtil.getCurrentTime()));

			accept.setPhoto_1(photo_1);
			accept.setPhoto_2(photo_2);
			accept.setPhoto_3(photo_3);
			accept.setPhoto_4(photo_4);
	
			
			
			/*********************************************************20170316  101接口修改  原业务逻辑更改前begin********************************************************************************************/
//			if(flag.endsWith("1"))
//			{	
//				//vinNum engineNum brandModel plateOrTireExterior tireIntact seatBelt
//				accept.setVinNum("1");
//				accept.setEngineNum("1");
//				accept.setBrandModel("1");
//				accept.setPlateOrTireExterior("1");
//				accept.setTireIntact("1");
//				accept.setSeatBelt("1");
//				
//				status = TmsXmlResolveDataBaseTransUtil.checkImg(accept);
//			}
////			if(flag.endsWith("2")) {//屏蔽车辆查验功能	
////				status = TmsXmlResolveDataBaseTransUtil.checkCar(accept);
////			}
//			if(flag.endsWith("3"))
//			{	
//				status =  TmsXmlResolveDataBaseTransUtil.checkAgain(accept);
//			}
			
			/*********************************************************20170316  101接口修改  原业务逻辑更改前end*****************************************************************************************************************/
			
			/*********************************************************20170316  101接口修改  原业务逻辑更改后begin********************************************************************************************/
			
			accept.setVinNum("1");
			accept.setEngineNum("1");
			accept.setBrandModel("1");
			accept.setPlateOrTireExterior("1");
			accept.setTireIntact("1");
			accept.setSeatBelt("1");
			
			status = TmsXmlResolveDataBaseTransUtil.checkImg(accept);
			
			/*********************************************************20170316  101接口修改  原业务逻辑更改后end********************************************************************************************/
			

			} catch (TmsDaoException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		logger.debug("车辆信息同步结束.........................");
		return status;
	}
	
 

	/**
	 * 交易车辆查验车辆基本信息、图片数据同步下载
	 * 
	 * @param serial
	 * @param licenseplate
	 * @return
	 */

	public static String loadCarInfo(String serial, String licenseplate) {
		logger.debug(" 交易车辆查验车辆基本信息、图片数据同步下载同步开始.........................");
		String xml = "";
		TxController controller = TxController.getTxController();
		try {
			controller.begin();
			// 直接在过户表中查询过户信息
            if(serial.length()==7)
            {
            	licenseplate=serial;	
            	serial=null;
            }	
			TransferAcceptedInfo accept = new TransferAcceptedInfo();
			accept =  TmsXmlResolveDataBaseTransUtil.loadCarInfo(serial, licenseplate);
			if (accept != null) {
				String photo1 = "";
				String photo2 = "";
				String photo3 = "";
				String photo4 = "";
				if(accept.getPhoto_1()!=null&&!"".equals(accept.getPhoto_1()))
				{
					photo1=Registry.getConfig(TmsConstants.PAD_HOST_KEY)+accept.getPhoto_1();
				}
				if(accept.getPhoto_2()!=null&&!"".equals(accept.getPhoto_2()))
				{
					photo2=Registry.getConfig(TmsConstants.PAD_HOST_KEY)+accept.getPhoto_2();
				}
				if(accept.getPhoto_3()!=null&&!"".equals(accept.getPhoto_3()))
				{
					photo3=Registry.getConfig(TmsConstants.PAD_HOST_KEY)+accept.getPhoto_3();
				}
				if(accept.getPhoto_4()!=null&&!"".equals(accept.getPhoto_4()))
				{
					photo4=Registry.getConfig(TmsConstants.PAD_HOST_KEY)+accept.getPhoto_4();
				}
				
                  int businesstype=2;
                  if(accept.getRegistration()!=0)
                  {
                	  businesstype=accept.getRegistration();
                	  
                  }	  
                  if(accept.getTransfer()!=0)
                  {
                	  businesstype=accept.getTransfer();
                	  
                  }
                  if(accept.getTransferRegister()!=0)
                  {
                	  businesstype=accept.getTransferRegister();
                	  
                  }
                  String cardType="1";
                  if(accept.getCy_cardType().equals("0"))
                  {
                	  cardType="1";
                  }
                  if(accept.getCy_cardType().equals("1"))
                  {
                	  cardType="2";
                  } 
                  if(accept.getCy_cardType().equals("2"))
                  {
                	  cardType="3";
                  } 
				xml = "<?xml version='1.0' encoding='utf-8'?>" + "<Cars>"
						+ "<serial>"
						+ StringUtil.escapeSingleQuotations(accept.getSerial())
						+ "</serial>"
						+ "<licenseplate>"
						+ StringUtil.escapeSingleQuotations(accept.getLicensePlate())
						+ "</licenseplate>"
						+ "<vin>"
						+ StringUtil.escapeSingleQuotations(accept.getVin())
						+ "</vin>"
						+ "<cy_cardtype>"
						+ StringUtil.escapeSingleQuotations(cardType)
						+ "</cy_cardtype>"
						+ "<businesstype>"
						+ businesstype
						+ "</businesstype>"
						+ "<vinnum>"
						+ StringUtil.escapeSingleQuotations(accept.getVinNum())
						+ "</vinnum>"
						+ "<enginenum>"
						+ StringUtil.escapeSingleQuotations(accept.getEngineNum())
						+ "</enginenum>"
						+ "<brandmodel>"
						+StringUtil.escapeSingleQuotations( accept.getBrandModel())
						+ "</brandmodel>"
						+ "<cy_color>"
						+StringUtil.escapeSingleQuotations( accept.getCy_color())
						+ "</cy_color>"
						+ "<cy_passenger>"
						+StringUtil.escapeSingleQuotations( accept.getCy_passenger())
						+ "</cy_passenger>"
						+ "<cy_cartype>"
						+StringUtil.escapeSingleQuotations( accept.getCy_carType())
						+ "</cy_cartype>"
						+ "<plateortireexterior>"
						+ StringUtil.escapeSingleQuotations(accept.getPlateOrTireExterior())
						+ "</plateortireexterior>"
						+ "<tireIntact>"
						+StringUtil.escapeSingleQuotations( accept.getTireIntact())
						+ "</tireIntact>"
						+ "<seatbelt>"
						+StringUtil.escapeSingleQuotations( accept.getSeatBelt())
						+ "</seatbelt>"
						+ "<numberAxes>"
						+StringUtil.escapeSingleQuotations( accept.getNumberAxes())
						+ "</numberAxes>"
						+ "<tiresize>"
						+StringUtil.escapeSingleQuotations( accept.getTireSize())
						+ "</tiresize>"
						+ "<lateralportionof>"
						+StringUtil.escapeSingleQuotations( accept.getLateralPortionOf())
						+ "</lateralportionof>"
						+ "<reflectivemark>"
						+ StringUtil.escapeSingleQuotations(accept.getReflectiveMark())
						+ "</reflectivemark>"
						+ "<fireextinguisher>"
						+StringUtil.escapeSingleQuotations( accept.getFireExtinguisher())
						+ "</fireextinguisher>"
						+ "<drivingrecord>"
						+ StringUtil.escapeSingleQuotations(accept.getDrivingRecord())
						+ "</drivingrecord>"
						+ "<security>"
						+ StringUtil.escapeSingleQuotations(accept.getSecurity())
						+ "</security>"
						+ "<externalmarking>"
						+ StringUtil.escapeSingleQuotations(accept.getExternalMarking())
						+ "</externalmarking>"
						+ "<siren>"
						+ StringUtil.escapeSingleQuotations(accept.getSiren())
						+ "</siren>"
						+ "<securitytechnology>"
						+StringUtil.escapeSingleQuotations( accept.getSecurityTechnology())
						+ "</securitytechnology>"
						+ "<checkconclusion>"
						+ StringUtil.escapeSingleQuotations(accept.getCheckConclusion())
						+ "</checkconclusion>"
						+"<inserttime>"
						+StringUtil.escapeSingleQuotations(accept.getInsertTimeS())
						+"</inserttime>"
						+ "<photo_1>"
						+photo1
						+ "</photo_1>"
						+ "<photo_2>"
						+photo2
						+ "</photo_2>"
						+ "<photo_3>"
						+ photo3
						+ "</photo_3>"
						+ "<photo_4>"
						+photo4
						+ "</photo_4>"
						+ "</Cars>";

			} else {
				controller.commit();
				logger.error("无匹配数据!");
				return null;
			}
			controller.commit();

		} catch (TransactionException e) {
			logger.error("出现异常" + e.getMessage());
			return null;
		}
		logger.debug(" 交易车辆查验车辆基本信息、图片数据同步下载同步结束.........................");
		return xml;
	}

	/**
	 * 库存查验车辆基本信息、图片数据同步
	 * 
	 * @param licensePlate
	 *            车牌号码
	 * @param memberId
	 *            会员ID
	 * @param mileage
	 *            表显里程
	 * @param price
	 *            预售价格
	 * @param carImages_1
	 * @param carImages_2
	 * @param carImages_3
	 * @param carImages_4
	 * @param userId
	 *            操作用户
	 * @param insertTime
	 *            插入时间
	 * @return
	 */
	public static String loadMarketCarInfo(String licensePlate,
			String memberId, String mileage, String price, String carImages_1,
			String carImages_2, String carImages_3, String carImages_4,
			String carImages_5, String carImages_6, String carImages_7,
			String carImages_8,
			String userId, String insertTime) {
		logger.debug("库存查验车辆基本信息、图片数据同步start........................");
		String status = "1";	
		String flag= "";
		if(StringUtil.isNullOrBlank(licensePlate)){
			status="2";
		    logger.debug("车牌号码不能为空!");
		    return status;
		}
		if(licensePlate.length()!=7 &&!licensePlate.equals(""))
		{
			status="2";
		    logger.debug("PAD查验车牌号码不是七位!");
		    return status;
		}	
//		if("".equals(carImages_1) && "".equals(carImages_2) && "".equals(carImages_3) && "".equals(carImages_4) 
//				&&"".equals(carImages_5) && "".equals(carImages_6) && "".equals(carImages_7) && "".equals(carImages_8) 	)
//		{
//			status="2";
//		    logger.debug("PAD查验图片全部为空!");
//		    return status;
//		}	
		if("".equals(userId))
		{
			status="2";
		    logger.debug("PAD查验图片userid为空!");
		    return status;
		}	
		try {
			
		    Car car = Car.getInstance();
			// 更新过户表
			
			car.setLicensePlate(licensePlate);
			car.setPhoto_1(carImages_1);
			car.setPhoto_2(carImages_2);
			car.setPhoto_3(carImages_3);
			car.setPhoto_4(carImages_4);
			car.setPhoto_5(carImages_5);
			car.setPhoto_6(carImages_6);
			car.setPhoto_7(carImages_7);
			car.setPhoto_8(carImages_8);
			if(!StringUtil.isNullOrBlank(mileage)){
				car.setMileage(Integer.parseInt(mileage));
			}else{
				car.setMileage(0);
			}
			if(!StringUtil.isNullOrBlank(memberId)){
				car.setMemberId(Integer.parseInt(memberId));
			}else{
				car.setMemberId(0);
			}
			if(!StringUtil.isNullOrBlank(price)){
				car.setPrice(Integer.parseInt(price));
			}else{
				car.setPrice(0);
			}
			

			User user = new User();
			user = user.getUserProfileByLoginid(userId, "");
			if(user!=null)
			{
				car.setInsertUserId(user.getId());
				car.setUpdateUserId(user.getId());
			}else{
				car.setInsertUserId(1);
				car.setUpdateUserId(1);
			}
			status = TmsXmlResolveDataBaseTransUtil.checkMarketCar(car);
	
			

			} catch (TmsDaoException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		logger.debug("库存查验车辆基本信息、图片数据同步end........................");
		return status;
	}

	/**
	 * 库存查验会员信息同步
	 * 
	 * @return
	 */
	public static String loadMember() {
		logger.debug("经济公司信息同步开始...");
		TxController controller = TxController.getTxController();
		try {
			controller.begin();
			Member member = Member.getInstance();
			// 传递原始信息
			List list = member.findAllMemInfo();
			if (list.size() < 1) {
				controller.commit();
				logger.debug("未取到会员信息！");
				return null;
			}
			String xml = "<?xml version='1.0' encoding='utf-8'?><Member>";
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map) list.get(i);
				xml += "<Members>" + "<MemberId>"
						+ map.get(TmsXmlConstants.MEMBERID) + "</MemberId>"
						+ "<MemberName>" + map.get(TmsXmlConstants.MEMBERNAME)
						+ "</MemberName>" + "</Members>";
			}
			xml+= "</Member>";
			controller.commit();
			return xml;

		} catch (TransactionException e) {
			logger.error("出现异常" + e.getMessage());
		} catch (TmsDaoException e) {
			logger.error("出现异常" + e.getMessage());
		}
		return null;
	}

	/**
	 * try{
	 * 
	 * // 将图片转换成字符串 File f = new File("c:\\dasdasd.jpg"); FileInputStream fis =
	 * new FileInputStream( f ); byte[] bytes = new byte[fis.available()];
	 * fis.read(bytes); fis.close();
	 * 
	 * // 生成字符串 String imgStr = byte2hex( bytes ); System.out.println( imgStr);
	 * 
	 * 
	 * 
	 * // 将字符串转换成二进制，用于显示图片 // 将上面生成的图片格式字符串 imgStr，还原成图片显示 OutputStream o =
	 * response.getOutputStream();
	 * 
	 * 
	 * byte[] imgByte = hex2byte( imgStr ); InputStream in = new
	 * ByteArrayInputStream( imgByte );
	 * 
	 * byte[] b = new byte[1024]; int nRead = 0; while( ( nRead = in.read(b) )
	 * != -1 ){ o.write( b, 0, nRead ); } o.flush(); o.close(); in.close();
	 * 
	 * }catch(Exception e){ e.printStackTrace(); }finally{ }
	 * 
	 */

//	/**
//	 * 二进制转字符串
//	 */
//	public static String byte2hex(byte[] b) {
//		StringBuffer sb = new StringBuffer();
//		String stmp = "";
//		for (int n = 0; n < b.length; n++) {
//			stmp = Integer.toHexString(b[n] & 0XFF);
//			if (stmp.length() == 1) {
//				sb.append("0" + stmp);
//			} else {
//				sb.append(stmp);
//			}
//
//		}
//		return sb.toString();
//	}
//
//	/**
//	 * 字符串转二进制
//	 * 
//	 * @param str
//	 * @return
//	 */
//	public static byte[] hex2byte(String str) {
//		if (str == null)
//			return null;
//		str = str.trim();
//		int len = str.length();
//		if (len == 0 || len % 2 == 1)
//			return null;
//		byte[] b = new byte[len / 2];
//		try {
//			for (int i = 0; i < str.length(); i += 2) {
//				b[i / 2] = (byte) Integer
//						.decode("0X" + str.substring(i, i + 2)).intValue();
//			}
//			return b;
//		} catch (Exception e) {
//			return null;
//		}
//	}

//	/**
//	 * 将图片转换成字符串工具
//	 * 
//	 * @throws IOException
//	 */
//	private static String transPicToStr(String serial, String imgPath)
//			throws IOException {
//		File f = new File(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD + "/" + serial
//				+ "/" + imgPath);
//		FileInputStream fis = new FileInputStream(f);
//		byte[] bytes = new byte[fis.available()];
//		fis.read(bytes);
//		fis.close();
//		return byte2hex(bytes);
//	}
	/**
	 * 图片转化成字符串
	 * @param args
	 * @throws IOException
	 */
	public static String transPicToStr(String serial,String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		//String imgFile = "d:\\111.jpg";// 待处理的图片
		File f = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY) + "/" + serial+ "/" + imgFile));
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
		in = new FileInputStream(f);
		data = new byte[in.available()];
		in.read(data);
		in.close();
		} catch (IOException e) {
		e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
		}

		/**
		* 将字符串转为图片
		* @param imgStr
		* @return
		*/
		public static boolean generateImage(String imgStr,String imgFile)throws Exception {// 对字节数组字符串进行Base64解码并生成图片
			if (imgStr == null) // 图像数据为空
			return false;
			BASE64Decoder decoder = new BASE64Decoder();
			try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {// 调整异常数据
			b[i] += 256;
			}
			}
			// 生成jpeg图片
			String imgFilePath = imgFile;// 新生成的图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
			} catch (Exception e) {
			throw e;
			}
		}
		/**
		 * 图片上传处理工具
		 * 
		 * @param serial
		 * @param key
		 * @param imgStr
		 * @return
		 */
		private static String imageTool(String serial, String key, String imgStr) {
			String FileName =ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY) + "/" + serial + "/" + serial + "_" + key + ".jpg") ;
			// 图片名称
			File file = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY) + "/" + serial + "/"));
			boolean bsflag;
			try {
				bsflag = generateImage(imgStr,file +"/"+ serial + "_" + key + ".jpg");
				if (bsflag == false) {
					logger.error("图片" + key + "为空!");
					return "";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return FileName;
		}

//	 public static void main(String[] args) throws IOException {
//		 
////	System.out.println(getImageStr("c:\\asdadad.jpg")); 
//		 
//	 // 将图片转换成字符串
////	 File f = new File("c:\\asdadad.jpg"); 
////	 FileInputStream fis = new FileInputStream( f ); 
////	 byte[] bytes = new byte[fis.available()];
////	 fis.read(bytes); fis.close();
////			  
////	 String imgStr = byte2hex( bytes );
////	 System.out.println( imgStr);
//	 }
		

	
	 
}
